﻿using NHibernate;
using NHibernate.Cfg;

namespace Lyh.Core.Storage
{
    public static class SessionBuilder
    {
        private static readonly object Locker = new object();
        private static Configuration configuration;
        private static ISessionFactory sessionFactory;
        public static ISessionStorage SessionStorage { set; get; }

        private static void CreateConfiguration()
        {
            HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();//查看HQL生成的SQL
            configuration = new Configuration().Configure();
        }

        public static Configuration Configuration
        {
            get
            {
                lock (Locker)
                {
                    if (configuration == null)
                    {
                        CreateConfiguration();
                    }
                    return configuration;
                }
            }
            set { configuration = value; }
        }

        internal static ISessionFactory SessionFactory
        {
            get
            {
                if (sessionFactory==null)
                {
                    if (Configuration == null)
                    {
                        CreateConfiguration();
                    }
                    lock (Locker)
                    {
                        sessionFactory = Configuration.BuildSessionFactory();
                    }
                }

                return sessionFactory;
            }
        }

        public static ISession CreateSession()
        {
            ISession s = null;
            if (SessionStorage != null) s = SessionStorage.Get();
            if (s == null)
            {
                s = SessionFactory.OpenSession();
                if (SessionStorage != null) SessionStorage.Set(s);
            }
            return s;
        }

        public static void CloseSessionFactory()
        {
            if (SessionFactory != null)
            {
                SessionFactory.Close();
            }
        }

    }
}
